import React, { useEffect, useState } from 'react';
import { Search, Tag, Space } from 'react-vant'

const Index = () => {
  // 使用useState设置一个变量searchList，用来存储从本地存储中获取的搜索列表，如果没有获取到，则设置为空数组
  const [searchList, setSearchList] = useState(JSON.parse(localStorage.getItem('searchList')) || [])
  // 搜索
  const onSearch = (value) => {
    // 插入到前面, 去重复 searchList
    setSearchList([...new Set([value, ...searchList])])
  }

  // 关闭
  const close = (item) => {
    // 过滤掉searchList中的item
    setSearchList(searchList.filter(v => v !== item))
  }


  useEffect(() => {
    // 将搜索列表存储到本地
    localStorage.setItem('searchList', JSON.stringify(searchList))
  }, [searchList])
  return (
    <div>
      <Search placeholder='请输入关键字' onSearch={onSearch}></Search>
      <div className='search-result'>
        <h4>
          <span>历史记录</span>
          <span onClick={() => setSearchList([])}>清空</span>
        </h4>
        {/* 渲染历史记录 */}
        <Space>
          {searchList.map(
            (item, index) => <Tag onClose={() => close(item)} closeable key={index} type="primary">{item}</Tag>
          )}
        </Space>
      </div>
    </div>
  )
}

export default Index